package com.woniuxy.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.memory.redis.RedisChatMemoryRepository;
import com.woniuxy.service.UserService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 马宇航
 * @Description: AI搭建本地的磁盘的向量数据业务
 * @DateTime: 25/10/30/星期四 17:38
 * @Component: 成都蜗牛学苑
 **/
@RestController
@RequestMapping("/vector")
public class AiVectorController {
    static final String PATH = "D:\\Desktop\\116期\\redisproject\\java116-rag\\src\\main\\resources\\vector";
    SimpleVectorStore vectorStore;
    @Autowired
    ChatClient chatClient;

    @Autowired
    public AiVectorController(EmbeddingModel embeddingModel) {
        this.vectorStore = SimpleVectorStore.builder(embeddingModel).build();
    }

    @GetMapping("/add")
    public String vector(String msg){
        //在内存中，把文本向量化
        vectorStore.add(Arrays.asList(new Document(msg)));
        //把内存中的向量数据，持久化到磁盘
        vectorStore.save(new File(PATH + "\\simple.json"));
        return PATH;
    }
    @GetMapping("/search")
    public String vectorSearch(String msg){
        //磁盘数据加载到内存
        vectorStore.load(new File(PATH + "\\simple.json"));
        //在内存中，根据文本向量化，查询最相似的文档
        List<Document> documents = vectorStore.similaritySearch(SearchRequest.builder()
                .query(msg)
                .topK(2) // 返回前2个最相似的文档
                .similarityThreshold(0.5) // 相似度阈值，默认0.75，只有相似度大于等于该值才会返回
                .build());
        return chatClient.prompt(documents.toString() + "，请根据以上文档，回答我的问题：" + msg).call().content();
    }
}
